package com.lzy.shops.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzy.shops.bean.User;
import com.lzy.shops.service.UserService;
import com.lzy.shops.utils.ResponseData;
import com.lzy.shops.utils.TokenTask;
import com.lzy.shops.utils.exception.ExistException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/index/register")
    public String register(@RequestBody User user) throws JsonProcessingException {
        Integer integer = null;
        ResponseData<User> responseData;
        try {
            integer = userService.registerUser(user);
            if(integer!=0){
                responseData = new ResponseData<>(true,"注册成功!");
            }else{
                responseData = new ResponseData<>(false,"注册失败！");
            }
        } catch (ExistException e) {
            responseData = new ResponseData<>(false,"用户已存在，请重试！");
        }
        ObjectMapper jsonObje = new ObjectMapper();
        return jsonObje.writeValueAsString(responseData);
    }

    @PutMapping("/update")
    public String update(@RequestBody User user){
        Integer integer = userService.updateUser(user);
        if(integer != null || integer !=0){
            return "true";
        }
        return "false";
    }

    @DeleteMapping("/delete/{id}")
    public String update(@PathVariable("id") Integer id){
        Integer integer = userService.deleteUser(id);
        if(integer != null || integer !=0){
            return "true";
        }
        return "false";
    }

    @PutMapping("/editPassword")
    public String editPassword(@RequestBody User user){
        Integer integer = userService.updatePassword(user);
        if(integer != null || integer !=0){
            return "true";
        }
        return "false";
    }

    @PostMapping("/index/login")
    public String login(@RequestBody Map<String,Object> para) throws JsonProcessingException {
        String username=(String)para.get("username");
        String password=(String)para.get("password");
        // 查询数据库中注册的用户
        User resultUser = userService.findByUser(new User(username, password));
        // 验证请求是否正确
        if(resultUser == null || !(resultUser.getPassword().equals(password))){
            return objectMapper.writeValueAsString(new ResponseData<User>(false,"用户名或密码错误"));
        }else{
            // 返回token
            String token= TokenTask.sign(new User(username,password));
            // 更新用户信息
            userService.loginUser(new User(resultUser.getId(),new Date()));
            return objectMapper.writeValueAsString(new ResponseData<String>(true,token,"token令牌"));
        }
    }

    @GetMapping("/index/findByUser")
    public String findByUser(@RequestParam("username") String username){
        User userInfo = userService.findByUser(new User(username));
        if(userInfo == null){
            return "true";
        }else{
            return "false";
        }
    }

    @GetMapping("findByUserInfo")
    public String findByUserInfo(@RequestParam("username") String username) throws JsonProcessingException {
        User userInfo = userService.findByUser(new User(username));
        StringBuilder sb = new StringBuilder();
        if(userInfo != null){
            sb.append("{");
            if(!userInfo.getAnotherName().isEmpty()){
                sb.append("\"aName\":\""+userInfo.getAnotherName()+"\"");
                if(userInfo.getId()!=null&&userInfo.getId()!=0){
                    sb.append(",");
                }
            }
            if(userInfo.getId()!=null&&userInfo.getId()!=0){
                sb.append("\"id\":\""+userInfo.getId()+"\"");
            }
            sb.append("}");
            return objectMapper.writeValueAsString(new ResponseData<StringBuilder>(true,sb));
        }else{
            return "false";
        }
    }

    @GetMapping("/findById/{userId}")
    public String findById(@PathVariable("userId") Integer id) throws JsonProcessingException {
        User user = userService.findById(id);
        ResponseData<User> response = null;
        if(user!=null){
            response = new ResponseData<User>(true,user);
        }else{
            response = new ResponseData<User>(false,"查找失败");
        }
        return objectMapper.writeValueAsString(response);
    }
}
